package com.ekuaitu.kuaitu.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.ParkBean;
import com.ekuaitu.kuaitu.map.GeocodeSearchViewUtils;
import com.ekuaitu.kuaitu.map.MarkerUtils;
import com.ekuaitu.kuaitu.map.RoutePlanUtils;
import com.ekuaitu.kuaitu.map.SensorEventHelper;
import com.ekuaitu.kuaitu.utils.AppManager;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.widget.Toast.LENGTH_LONG;

public class InUseMapActivity extends Activity implements AMapLocationListener, AMap.OnMarkerClickListener {
    @BindView(R.id.return_inuse_map)
    ImageView return_inuse_map;
    @BindView(R.id.inuse_mapView)
    MapView inuseMapView;
    @BindView(R.id.activity_in_use_map)
    RelativeLayout activityInUseMap;
    @BindView(R.id.progressBar_inuse_map)
    LinearLayout progressBar_inuse_map;
    @BindView(R.id.tv_inuse_map_position)
    TextView tvInuseMapPosition;
    @BindView(R.id.tv_inuse_map_navi)
    TextView tvInuseMapNavi;
    @BindView(R.id.lin_inuse)
    LinearLayout linInuse;
    private ArrayList<Marker> markerList = new ArrayList<>();
    private AMap aMap = null;
    private UiSettings mUiSettings = null;
    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = null;
    private Context mContext = this;
    private LatLng curPosition;
    private MarkerUtils myMarker;
    private List<ParkBean.AttachmentBean.ParksBean> parksResult;
    private LatLng parkPostion;
    private Marker locationMarker;
    private MarkerUtils markerUtils;
    private boolean isFirstLocation = true;
    private SensorEventHelper mSensorHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_in_use_map);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary), 0,false);
        ButterKnife.bind(this);
        inuseMapView.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        initData();
        initMap();
    }

    private void initMap() {
        aMap = inuseMapView.getMap();
        aMap.setMapType(AMap.MAP_TYPE_NAVI);
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setMyLocationButtonEnabled(false); // 显示默认的定位按钮
        aMap.setMyLocationEnabled(true);// 可触发定位并显示定位层
        aMap.setOnMarkerClickListener(this);
        mUiSettings.setScaleControlsEnabled(true);//显示比例尺控件
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setTiltGesturesEnabled(false);
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(2000);
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        markerUtils = new MarkerUtils(mContext, aMap);
    }

    private void initData() {
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        linInuse.setVisibility(View.VISIBLE);
        tvInuseMapPosition.setText("正在规划路线...");
        routePlanning(marker.getPosition());
        parkPostion = marker.getPosition();
        GeocodeSearchViewUtils geocodeSearchViewUtils1 = new GeocodeSearchViewUtils();
        geocodeSearchViewUtils1.startGeocodeSearch(mContext, marker.getPosition().latitude, marker.getPosition().longitude, tvInuseMapPosition);
        return false;
    }

    private void routePlanning(LatLng tarPosition) {
        if (curPosition != null) {
            RoutePlanUtils.getInstance().startRoutePlanning(mContext, aMap, curPosition, tarPosition,true,null);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();
        mLocationClient.onDestroy();
        inuseMapView.onDestroy();
        aMap = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        inuseMapView.onResume();
        initSensor();
    }

    private void initSensor() {
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        } else {
            mSensorHelper = new SensorEventHelper(this);
            if (mSensorHelper != null) {
                mSensorHelper.registerSensorListener();
                if (mSensorHelper.getCurrentMarker() == null && locationMarker != null) {
                    mSensorHelper.setCurrentMarker(locationMarker);
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        inuseMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        inuseMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            curPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            // 定位成功后把地图移动到当前可视区域内
            if (isFirstLocation) {
                aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 15, 0, 0)));
                isFirstLocation = false;
                locationMarker = markerUtils.addLocationIcon(curPosition);
                locationMarker.setClickable(false);
                mSensorHelper.setCurrentMarker(locationMarker);
                getParks();
            } else {
                locationMarker.setPosition(curPosition);
            }
        } else {
            mLocationClient.startLocation();
        }
    }


    public void getParks() {
        progressBar_inuse_map.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getParks(MyApplication.getInstance().getRequestFieldMap(),"1", "3000")
                .enqueue(new Callback<ParkBean>() {
                    @Override
                    public void onResponse(Call<ParkBean> call, Response<ParkBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            progressBar_inuse_map.setVisibility(View.GONE);
                            if (response.body().getStatus() == 200) {
                                if (markerList != null) {
                                    for (Marker marker : markerList) {
                                        marker.remove();
                                    }
                                }
                                parksResult = response.body().getAttachment().getParks();
                                //添加网点标记
                                myMarker = new MarkerUtils(mContext, aMap);
                                for (int i = 0; i < parksResult.size(); i++) {
                                    markerList.add(myMarker.addCarMarkerToMap(parksResult.get(i).getLatitude(), parksResult.get(i).getLongitude()));
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ParkBean> call, Throwable t) {
                        progressBar_inuse_map.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @OnClick({R.id.return_inuse_map, R.id.tv_inuse_map_navi})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_inuse_map:
                finish();
                break;
            case R.id.tv_inuse_map_navi:
                Intent intent = new Intent(mContext, NaviActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("latitude", curPosition.latitude + "");
                bundle.putString("longitude", curPosition.longitude + "");
                bundle.putString("toLatitude", parkPostion.latitude + "");
                bundle.putString("toLongitude", parkPostion.longitude + "");
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }

    @OnClick(R.id.iv_order_map_locate)
    public void onClick() {
        if (curPosition != null) {
            aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 15, 0, 0)));
        } else {
            ToastCompat.makeText(mContext, "正在定位...", Toast.LENGTH_SHORT).show();
        }
    }
}
